package ru.belokuriha_online.resort_hotels_belokuriha;


import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.content.Context;
import android.net.ConnectivityManager;


public class MyAmsService extends Service {
	int Stopservice;
	int queryload;
	ExecutorService es;
	String myurl;
	String myflos;
	String vermyurl;
	String vermyflos;
	File flsd;
	URL url1;
	String SUB_HOST;
	HttpURLConnection urlConnection1;
	Intent intent = new Intent();
	PendingIntent pi;
	int vidload;
	int peredrezult;


	public void onCreate() { 

		super.onCreate();

		es = Executors.newFixedThreadPool(1); 
	} 

	public void onDestroy() {
		super.onDestroy();      
		//


	} 

	public int onStartCommand(Intent intent, int flags, int startId) { 
		//   

		int runs = intent.getIntExtra(MainActivity.PARAM_RUNS, 1); 
		int task = intent.getIntExtra(MainActivity.PARAM_TASK, 0);
		String spprisepath = intent.getStringExtra("spprisepath");
		PendingIntent pi = intent.getParcelableExtra(MainActivity.PARAM_PINTENT); 

		MRun mrf = new MRun(spprisepath, runs, startId, task, pi);     
		es.execute(mrf);

		return super.onStartCommand(intent, flags, startId); 
	}




	public IBinder onBind(Intent arg0) { 
		return null; 
	} 

	class MRun implements Runnable { 
		PendingIntent pi;
		String spprisepath;
		int runs; //
		int startId; 
		int task; 
		String names_san1;
		int rezimload;

		public MRun(String spprisepath,int runs, int startId, int task, PendingIntent pi) {
			this.spprisepath = spprisepath;
			this.runs = runs; 
			this.startId = startId; 
			this.task = task;
			this.pi = pi; 

		} 

		public void run() {
			Stopservice = 0;
			queryload = 0;

			SUB_HOST = getString(R.string.SUB_HOST);
			// 
			try {
				if (runs == 1) {
					//
					intent.putExtra(MainActivity.PARAM_TASK, task); 
					intent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_START); 

					pi.send(MyAmsService.this, MainActivity.STATUS_START, intent);
				}
				// 
				/////


				String myflos = spprisepath+ File.separator+ getString(R.string.app_price);

				String myurl = SUB_HOST+ getString(R.string.app_price); 
				//

				if (loadFileos(myflos, myurl, 0, runs)==true) {
					try {


						XmlPullParserFactory parserpull = XmlPullParserFactory.newInstance();
						parserpull.setValidating(false);
						XmlPullParser parser = parserpull.newPullParser();

						File xmlfileprices1 = new File(myflos);
						InputStream xmlfile = new FileInputStream(xmlfileprices1);
						parser.setInput(xmlfile, null);

						while ((parser.getEventType()!= XmlPullParser.END_DOCUMENT) && (Stopservice == 0)) {
							if  (parser.getEventType() == XmlPullParser.START_TAG
									&& parser.getName().equals("sanatori") 
									&& parser.getDepth() == 2) {

								if (parser.getAttributeValue(1) == null) {
									names_san1 = ""; 
								} else {
									names_san1 = parser.getAttributeValue(1);			
								}
								String sanico = parser.getAttributeValue(2);
								if ((sanico != null) && !sanico.equals("") ){
									loadFileos(spprisepath+ File.separator + sanico, SUB_HOST+sanico, 1, runs); 
								}

							}	


							if  (parser.getEventType() == XmlPullParser.START_TAG
									&& parser.getName().equals(names_san1 + "_short") 
									&& parser.getDepth() == 3) {

								String abouts1 = parser.getAttributeValue(0);			
								if (abouts1 != null && !abouts1.equals("")) {


									loadFileos(spprisepath+ File.separator + abouts1, SUB_HOST+abouts1, 1, runs);
								}

							}
							parser.next();
						}
						xmlfile.close();

					}
					catch (Throwable t) {

					}  

				}

				/////

				// 
				Stopservice = 1;
				if (queryload == 0) {
					intent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_FINISH); 
					if (peredrezult == 1) {
						intent.putExtra(MainActivity.PARAM_RESULT, 1);
					}
					if (!(inWork(SUB_HOST+ getString(R.string.app_price))) && (runs == 1)) {
						intent.putExtra(MainActivity.PARAM_RESULT, 2);
					}
					
					pi.send(MyAmsService.this, MainActivity.STATUS_FINISH, intent);

				}
				else {
					
					intent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_QUERY); 
				
					pi.send(MyAmsService.this, MainActivity.STATUS_QUERY, intent);  
				}

			} catch (Exception e) { 
				e.printStackTrace(); 
			} 
			stopSelfResult(startId); 
		}






	} 

	///

	private boolean inWork(String myurln) throws Exception {

		while(true) {

			try {

				if ((isOnline()==true) && (readFurl(myurln)==true)) {


					return true;            
				}
				else {

					return false;
				}
			} catch (Exception e) {


				e.printStackTrace();
				return false;
			}


		}
	}

	private boolean readFurl(String myurln) throws Exception {

		HttpURLConnection conn = (HttpURLConnection) new URL(myurln).openConnection();
		conn.setUseCaches(false);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		int respCode = -1;
		for (int i=0; i<10 && respCode != HttpURLConnection.HTTP_OK; i++){
			respCode = conn.getResponseCode();

			Thread.sleep(10);
		}
		if (respCode != HttpURLConnection.HTTP_OK) {        	   


			return false;
		}
		else {	


			return true;
		}


	}

	private boolean isOnline() {
		ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMgr.getActiveNetworkInfo() == null && !(conMgr.getActiveNetworkInfo().isConnected())) {

			return false;
		}

		return true;
	}

	private boolean isFos(String myflosn) {


		File flsdn = new File(myflosn);
		if (!flsdn.exists()) {
			flsdn.getParentFile().mkdirs();

			return false;  	 
		}
		else {

			return true;	
		}

	}

	private boolean downloadFile(String myflosn, String myurln) {
		URL urll;    
		HttpURLConnection urlConnectionl;
		InputStream inputStream;
		byte[] buffer;
		int bufferLength;



		FileOutputStream fos = null;

		try {
			urll = new URL(myurln);
			urlConnectionl = (HttpURLConnection) urll.openConnection();

			urlConnectionl.setRequestMethod("GET");
			urlConnectionl.setDoOutput(true);
			urlConnectionl.connect();

			String flos = new String(myflosn);
			File fl = new File(flos);    
			fos = new FileOutputStream(fl);
			inputStream = urlConnectionl.getInputStream();


			buffer = new byte[1024];

			bufferLength = 0;

			//

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fos.write(buffer, 0, bufferLength);


			}

			fos.close();
			inputStream.close();
			return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}



	}

	//
	private boolean loadFileos(String myflosn, String myurln,int vidloadn, int prinudloadn) throws Exception { 
		int	 resultload = 0;
		isFos(myflosn);

		//

		if (inWork(myurln)) {
			//
			if (vidloadn == 0) {

				if (prinudloadn == 0) {

					try {
						XmlPullParserFactory parserpull = XmlPullParserFactory.newInstance();
						parserpull.setValidating(false);
						XmlPullParser parserflos = parserpull.newPullParser();
						File xmlflos = new File(myflosn);
						InputStream xmlfile = new FileInputStream(xmlflos);
						parserflos.setInput(xmlfile, null);

						while (parserflos.getEventType()!= XmlPullParser.END_DOCUMENT) {
							if (parserflos.getEventType() == XmlPullParser.START_TAG
									&& parserflos.getName().equals("updates")) {
								//
								vermyflos = parserflos.getAttributeValue(0);	
								//	
							}
							parserflos.next();
						}
						xmlfile.close();  
					}
					catch (Throwable t) {

					}

					try {
						URL urld = new URL(myurln);
						HttpURLConnection urlConnectiond = (HttpURLConnection) urld.openConnection();
						urlConnectiond.setRequestMethod("GET");
						urlConnectiond.setDoOutput(true);
						urlConnectiond.connect(); 
						XmlPullParserFactory parserpull = XmlPullParserFactory.newInstance();
						parserpull.setValidating(false);
						XmlPullParser parserflos = parserpull.newPullParser();
						InputStream xmlmyurl = urlConnectiond.getInputStream();;
						parserflos.setInput(xmlmyurl, null);

						while (parserflos.getEventType()!= XmlPullParser.END_DOCUMENT) {
							if (parserflos.getEventType() == XmlPullParser.START_TAG
									&& parserflos.getName().equals("updates")) {
								//
								vermyurl = parserflos.getAttributeValue(0);	
								//	
							}
							parserflos.next();
						}
						xmlmyurl.close(); 
					}
					catch (Throwable t) {

					}

					if ((vermyflos != null) & (vermyflos != null)) {
						if (vermyflos.toString().equals(vermyurl.toString())){


							resultload = 0;

						} 
						else {

							resultload = 0;
							queryload = 1;


						} 
					}
					else
					{
						resultload = 0;		  		

					}




				}
				else
				{
					if (downloadFile(myflosn, myurln)) {
						resultload = 1;

					}
					else {
						resultload = 0; 

					}	 
				}		  

			}
			else {



				if (downloadFile(myflosn, myurln)) {
					resultload = 1;

				}
				else {
					resultload = 0; 

				}

			}
		}
		else {

			resultload = 0;

		}          	  	  	 

		if (resultload == 1) {
			if (vidloadn == 0) {
				peredrezult = 1;	
			}

			return true;

		}
		else{
			if (vidloadn == 0) {
				peredrezult = 0;	 
			}

			return false;

		}
	} 
	// 
	///

}
